/**
 * @(#) ApprovalMediator.as
 *
 * @date		2010. 09. 08.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @client		Service Ace & Service Top 
 * @description	결재함 Mediator (결재함)
 * 				approval.ApprovalMediator에서 복사..
 */
package com.skt.common_hr.approval_sac.view
{
	import com.skt.common_hr.approval_sac.events.ApprovalListEvent;
	import com.skt.common_hr.approval_sac.events.ApprovalSearchEvent;
	import com.skt.common_hr.approval_sac.model.DeputyProxy;
	import com.skt.common_hr.approval_sac.model.PreApprovalProxy;
	import com.skt.common_hr.approval_sac.model.ToApprovalProxy;
	import com.skt.common_hr.approval_sac.model.vo.ApprovalListVO;
	import com.skt.common_hr.approval_sac.model.vo.DeputyVO;
	import com.skt.common_hr.approval_sac.view.components.ApprovalOverView;
	import com.skt.common_hr.approval_sac.view.components.PreApprovalView;
	import com.skt.common_hr.approval_sac.view.components.ToApprovalView;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.memberselector.MemberSelectorMediator;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class ApprovalMediator extends OverViewMediator
	{
		public static const NAME:String = "ApprovalMediator";
		private var bWaitingDelegator:Boolean = false;		
		private var deputyInfo:DeputyVO = null;
		private var bundle:String = "Approval";
		private var delegator:String = "";
		
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
		public function ApprovalMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
		override protected function initializeView():void 
 		{
 			super.initializeView();
 			setEventListeners();
 			callCheckDeputy();
 		}
 		
 		override protected function activatedView():void
 		{
 			loadApproval();
			if(Variables.moduleParams!=null) {
				if(Variables.moduleParams["SELECTED_APPROVAL_TYPE"]==1) {
					view.tnApp.selectedIndex = 1;
				}
				else {
					view.tnApp.selectedIndex = 0;
				}
				Variables.moduleParams["SELECTED_APPROVAL_TYPE"] = null;
			}
			setInitDates();
 		}
		
		private function initStatus():void
		{
 			view.viewPreAppList.cbStatus.selectedIndex = 0;
 			view.viewToAppList.cbAppCode.selectedIndex = 0;
		}
		
		override protected function closedView():void
		{
			removeEventListeners();	
			initStatus();
		}
		
		private function setEventListeners():void
		{
			view.viewToAppList.addEventListener(ApprovalListEvent.CHANGED_APPROVAL_FILTER, loadToAppList);
			view.viewToAppList.addEventListener(ApprovalListEvent.CHANGED_APPROVAL_DATE, loadToAppList);
			view.viewToAppList.addEventListener(ToApprovalView.EXEC_ACCEPT, execApproval);
			view.viewToAppList.addEventListener(ToApprovalView.EXEC_REJECT, execDeny);
			view.viewToAppList.addEventListener(ToApprovalView.EXEC_DELEGATION, selectDelegator);
			view.viewToAppList.addEventListener(ToApprovalView.EXEC_DEPUTY, execDeputy);
			view.viewToAppList.addEventListener(ToApprovalView.EXEC_DEPUTY_CLEAR, execDeputyClear);
			view.viewToAppList.addEventListener(ToApprovalView.EXEC_DEPUTY_INFO, execDeputyInfo);
			view.viewToAppList.addEventListener(ToApprovalView.SELECTED_ITEM, onSelectedApproval);
			view.viewPreAppList.addEventListener(PreApprovalView.LOAD_APPROVAL_LIST, loadPreAppList);
			view.viewPreAppList.addEventListener(ApprovalListEvent.CHANGED_APPROVAL_FILTER, loadPreAppList);
			view.viewPreAppList.addEventListener(ApprovalListEvent.CHANGED_APPROVAL_DATE, loadPreAppList);
			view.viewPreAppList.addEventListener(ApprovalSearchEvent.SEARCH_KEYWORD, preSearchKeyword);
			view.viewPreAppList.addEventListener(PreApprovalView.SELECTED_ITEM, onSelectedPreApproval);
		}
		
		private function removeEventListeners():void
		{
			view.viewToAppList.removeEventListener(ApprovalListEvent.CHANGED_APPROVAL_FILTER, loadToAppList);
			view.viewToAppList.removeEventListener(ApprovalListEvent.CHANGED_APPROVAL_DATE, loadToAppList);
			view.viewToAppList.removeEventListener(ToApprovalView.EXEC_ACCEPT, execApproval);
			view.viewToAppList.removeEventListener(ToApprovalView.EXEC_REJECT, execDeny);
			view.viewToAppList.removeEventListener(ToApprovalView.EXEC_DELEGATION, selectDelegator);
			view.viewToAppList.removeEventListener(ToApprovalView.EXEC_DEPUTY, execDeputy);
			view.viewToAppList.removeEventListener(ToApprovalView.EXEC_DEPUTY_CLEAR, execDeputyClear);
			view.viewToAppList.removeEventListener(ToApprovalView.SELECTED_ITEM, onSelectedApproval);
			view.viewPreAppList.removeEventListener(PreApprovalView.LOAD_APPROVAL_LIST, loadPreAppList);
			view.viewPreAppList.removeEventListener(ApprovalListEvent.CHANGED_APPROVAL_FILTER, loadPreAppList);
			view.viewPreAppList.removeEventListener(ApprovalListEvent.CHANGED_APPROVAL_DATE, loadPreAppList);
			view.viewPreAppList.removeEventListener(ApprovalSearchEvent.SEARCH_KEYWORD, preSearchKeyword);
			view.viewPreAppList.removeEventListener(PreApprovalView.SELECTED_ITEM, onSelectedPreApproval);
		}
		
		public function callCheckDeputy():void
		{
			var proxy:DeputyProxy = facade.retrieveProxy(DeputyProxy.NAME) as DeputyProxy;
			//proxy.checkDeputy(Variables.myPernr);
			proxy.loadDeputy(Variables.myPernr);	
		}
		
		public function loadApproval():void
		{
			/*
			var toProxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			toProxy.loadList(Variables.myPernr, "2");
			
			var preProxy:PreApprovalProxy  = facade.retrieveProxy(PreApprovalProxy.NAME) as PreApprovalProxy;
			preProxy.loadList(Variables.myPernr, "2");
			*/
			loadToAppList();
			loadPreAppList();
		}
		
		public function loadToAppList(e:ApprovalListEvent=null):void
		{
			var toProxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			if(view.viewToAppList.currentAppCode == "2") {
				toProxy.loadList(Variables.myPernr, view.viewToAppList.currentAppCode);
			}
			else {
				toProxy.loadList(Variables.myPernr, view.viewToAppList.currentAppCode, view.viewToAppList.dateBegin, view.viewToAppList.dateEnd);
			}
		}


		public function loadPreAppList(e:ApprovalListEvent=null):void
		{
			var preProxy:PreApprovalProxy = facade.retrieveProxy(PreApprovalProxy.NAME) as PreApprovalProxy;
			if(view.viewPreAppList.currentAppCode == "2") {
				preProxy.loadList(Variables.myPernr, view.viewPreAppList.currentAppCode);
			}
			else {
				preProxy.loadList(Variables.myPernr, view.viewPreAppList.currentAppCode, view.viewPreAppList.dateBegin, view.viewPreAppList.dateEnd);
			}
		}
		



		public function preSearchKeyword(e:ApprovalSearchEvent):void
		{
			var preProxy:PreApprovalProxy = facade.retrieveProxy(PreApprovalProxy.NAME) as PreApprovalProxy;
			preProxy.searchKeyword(Variables.myPernr, e.code, e.keyword);
		}

		private function setInitDates():void {
			var startDate:Date = new Date(2010, 6, 1);
			var d:Date = new Date();
			view.viewToAppList.dateEnd = new Date(d);
			view.viewPreAppList.dateEnd = new Date(d);
			d.month -= 1;
			d.date = 1;
			view.viewToAppList.dateBegin = new Date(d);
			view.viewPreAppList.dateBegin = new Date(d); 
		} 
		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return basicInterestMessages.concat([
					ToApprovalProxy.LOAD_TO_APPROVAL_LIST_COMPLETE,
					ToApprovalProxy.LOAD_TO_APPROVAL_LIST_FAILED,
					ToApprovalProxy.EXEC_ACCEPT_COMPLETE,
					ToApprovalProxy.EXEC_ACCEPT_FAILED,
					ToApprovalProxy.EXEC_DELEGATION_COMPLETE,
					ToApprovalProxy.EXEC_DELEGATION_FAILED,
					ToApprovalProxy.EXEC_REJECT_COMPLETE,
					ToApprovalProxy.EXEC_REJECT_FAILED,
					PreApprovalProxy.LOAD_PRE_APPROVAL_LIST_COMPLETE,
					PreApprovalProxy.LOAD_PRE_APPROVAL_LIST_FAILED,
					PreApprovalProxy.SEARCH_KEYWORD_COMPLETE,
					PreApprovalProxy.SEARCH_KEYWORD_FAILED,
					DeputyProxy.CHECK_DEPUTY_COMPLETE,
					DeputyProxy.CHECK_DEPUTY_FAILED,
					DeputyProxy.DELETE_DEPUTY_COMPLETE,
					DeputyProxy.DELETE_DEPUTY_FAILED,
					DeputyProxy.SAVE_DEPUTY_COMPLETE,
					DeputyProxy.SAVE_DEPUTY_FAILED,
					DeputyProxy.LOAD_DEPUTY_COMPLETE,
					DeputyProxy.LOAD_DEPUTY_FAILED,
					MemberSelectorMediator.SELECTED_MEMBER,
					MemberSelectorMediator.CANCEL_SELECTION,
					ApprovalViewMediator.CLOSED_APPROVAL_VIEW,
					ApprovalViewMediator.CANCEL_APPROVAL_VIEW
					]);
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName()) 
			{
				case DeputyProxy.CHECK_DEPUTY_COMPLETE:
					CommonAlert.showMsgYesNo("Approval", "ALERT_MSG_01", [Variables.myName], "ALERT_TITLE_DEFAULT", view, freeDeputy, null);
					break;
				case DeputyProxy.CHECK_DEPUTY_FAILED:
					break;
				case DeputyProxy.LOAD_DEPUTY_COMPLETE:
					deputyInfo = (note.getBody() as DeputyProxy).deputyInfo;
					if(deputyInfo!=null) {
						if(deputyInfo.CPERNR==Variables.myPernr) {
							CommonAlert.showMessage("Approval", "현재 "+deputyInfo.WNAME+"님의 대결자로 지정되어 있습니다.");
							view.viewToAppList.statusDeputy = 2;	
						}
						else {
							CommonAlert.showMsgYesNo("Approval", "ALERT_MSG_01", [Variables.myName], "ALERT_TITLE_DEFAULT", Sprite(view.root), freeDeputy, null);
							view.viewToAppList.statusDeputy = 1;		
						}
					}
					else {
						view.viewToAppList.statusDeputy = 0;
					}
					break;
				case DeputyProxy.DELETE_DEPUTY_COMPLETE:
					loadToAppList();
					CommonAlert.showMessage("Approval", "대결자지정이 해제 되었습니다.");
					view.viewToAppList.statusDeputy = 0;	
					break;
				case DeputyProxy.SAVE_DEPUTY_COMPLETE:
					loadToAppList();
					view.viewToAppList.statusDeputy = 1;	
					break;
				// 결재함 리스트 조회 성공
				case ToApprovalProxy.LOAD_TO_APPROVAL_LIST_COMPLETE:
					//trace("received LOAD_TO_APPROVAL_LIST_COMPLETE: " + ToApprovalProxy(note.getBody()).appList.length);
					view.viewToAppList.appList = ToApprovalProxy(note.getBody()).appList;
					if(view.viewToAppList.appList.length > 0) {
						commonFacade.setStatusMessage("STATUS_LOAD_LIST", [view.viewToAppList.appList.length]);
						commonFacade.showAlertMessage("STATUS_LOAD_LIST", [view.viewToAppList.appList.length]);
					}
					else {
						commonFacade.setStatusMessage("STATUS_LOAD_LIST_NODATA");
					}
					break;
				// 결재함 리스트 조회 실패
				case ToApprovalProxy.LOAD_TO_APPROVAL_LIST_FAILED:
					CommonAlert.showMessage("Approval", ToApprovalProxy(note.getBody()).retText, null, "ALERT_TITLE_ERROR", view);
					break;
					
				// 승인 성공
				case ToApprovalProxy.EXEC_ACCEPT_COMPLETE:
					loadToAppList();
					break;
				// 승인 실패
				case ToApprovalProxy.EXEC_ACCEPT_FAILED:
					CommonAlert.showMessage("Approval", ToApprovalProxy(note.getBody()).retText, null, "ALERT_TITLE_ERROR", view);
					break;
				// 반려 성공
				case ToApprovalProxy.EXEC_REJECT_COMPLETE:
					loadToAppList();
					break;
				// 반려 실패
				case ToApprovalProxy.EXEC_REJECT_FAILED:
					CommonAlert.showMessage("Approval", ToApprovalProxy(note.getBody()).retText, null, "ALERT_TITLE_ERROR", view);
					break;
				// 위임 성공
				case ToApprovalProxy.EXEC_DELEGATION_COMPLETE:
					loadToAppList();
					break;
				// 위임 실패
				case ToApprovalProxy.EXEC_DELEGATION_FAILED:
					CommonAlert.showMessage("Approval", ToApprovalProxy(note.getBody()).retText, null, "ALERT_TITLE_ERROR", view);
					break;
				// 결재 기안함 리스트 조회 성공
				case PreApprovalProxy.LOAD_PRE_APPROVAL_LIST_COMPLETE:
					view.viewPreAppList.appList = PreApprovalProxy(note.getBody()).appList;
					if(view.viewPreAppList.appList.length>0) {
						commonFacade.setStatusMessage("STATUS_LOAD_LIST", [view.viewPreAppList.appList.length]);
					}
					else {
						commonFacade.setStatusMessage("STATUS_LOAD_LIST_NODATA");
					}
					break;
				// 결재 기안함 리스트 조회 실패
				case PreApprovalProxy.LOAD_PRE_APPROVAL_LIST_FAILED:
					CommonAlert.showMessage("Approval", PreApprovalProxy(note.getBody()).retText, null, "ALERT_TITLE_ERROR", view);
					break;
				// 결재 기안함 키워드 검색 성공
				case PreApprovalProxy.SEARCH_KEYWORD_COMPLETE:
					view.viewPreAppList.appList = PreApprovalProxy(note.getBody()).appList;
					if(view.viewPreAppList.appList.length>0) {
						commonFacade.setStatusMessage("STATUS_LOAD_LIST", [view.viewToAppList.appList.length]);
					}
					else {
						commonFacade.setStatusMessage("STATUS_LOAD_LIST_NODATA");
					}
					break;
				// 결재 기안함 키워드 검색  실패
				case PreApprovalProxy.SEARCH_KEYWORD_FAILED:
					CommonAlert.showMessage("Approval", PreApprovalProxy(note.getBody()).retText, null, "ALERT_TITLE_ERROR", view);
					break;				
				// 구성원 선택  대화상자에서 구성원 선택
				case MemberSelectorMediator.SELECTED_MEMBER:
					if(bWaitingDelegator) {
						execDelegation(MemberSelectorMediator(note.getBody()).selectedMember.PERNR);
					}
					break;
				// 구성원 선택  대화상자에서 구성원 취소
				case MemberSelectorMediator.CANCEL_SELECTION:
					break;
				case ApprovalViewMediator.CLOSED_APPROVAL_VIEW:
					loadToAppList();
					break;
				case ApprovalViewMediator.CANCEL_APPROVAL_VIEW:
					//trace("ApprovalViewMediator.CANCEL_APPROVAL_VIEW");
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}

		private function freeDeputy():void
		{
			var proxy:DeputyProxy = facade.retrieveProxy(DeputyProxy.NAME) as DeputyProxy;
			proxy.delDeputy(Variables.myPernr);		
		}
		
		private var imTable:Array;
		private function execApproval(e:Event):void
		{
			imTable = getSelectedAppList(view.viewToAppList.appList);
			if(imTable.length<1) {
				CommonAlert.showMessage(bundle, "ALERT_NO_SELECTED");
				return;
			}
			else {
				CommonAlert.showMsgYesNo(bundle, "ALERT_COMFIRM_ACCEPT_ALL", [imTable.length], "TITLE_DEFAULT", Sprite(view.root),
									yesAccept, noprocess);
			}
		}		
		
		private function yesAccept():void
		{
			var proxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			proxy.acceptApproval("",  imTable);
		}

		private function noprocess():void
		{
		}
		private function execDeny(e:Event):void
		{
			imTable = getSelectedAppList(view.viewToAppList.appList);
			if(imTable.length<1) {
				CommonAlert.showMessage(bundle, "ALERT_NO_SELECTED");
				return;
			}
			else {
				CommonAlert.showMsgYesNo(bundle, "ALERT_COMFIRM_REJECT_ALL", [imTable.length], "TITLE_DEFAULT", view,
									yesReject, noprocess);
			}
			
		}		

		private function yesReject():void
		{
			var proxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			proxy.rejectApproval("", imTable);
		}

		private function selectDelegator(e:Event=null):void
		{
			imTable = getSelectedAppList(view.viewToAppList.appList);
			if(imTable.length<1) {
				CommonAlert.showMessage(bundle, "ALERT_NO_SELECTED");
				return;
			}

			var memberSelector:MemberSelectorMediator = 
					facade.retrieveMediator(MemberSelectorMediator.NAME) as MemberSelectorMediator;
			if(memberSelector==null) {
				memberSelector = new MemberSelectorMediator();
				facade.registerMediator(memberSelector);
			}
			memberSelector.exec(view);
			bWaitingDelegator = true;
			/*
			
			*/
		}		
		
		private function execDelegation(pernr:String):void
		{
			bWaitingDelegator = false;
			imTable = getSelectedAppList(view.viewToAppList.appList);
			if(imTable.length<1) {
				CommonAlert.showMessage(bundle, "ALERT_NO_SELECTED");
				return;
			}
			else {
				delegator = pernr;
				CommonAlert.showMsgYesNo(bundle, "ALERT_COMFIRM_DELEGATE_ALL", [imTable.length], "TITLE_DEFAULT", view,
										yesDelegation, noprocess);
			}			
		}
		
		private function yesDelegation():void
		{
			var proxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			proxy.delegateApproval(delegator, imTable);
		}
		
		private function execDeputy(e:Event=null):void
		{
			var deputy:DeputyMediator = facade.retrieveMediator(DeputyMediator.NAME) as DeputyMediator;
			if(deputy==null) {
				deputy = new DeputyMediator();
				facade.registerMediator(deputy);
			}
			deputy.execView(view);
			
		}
		
		private function execDeputyInfo(e:Event=null):void
		{
			var deputy:DeputyMediator = facade.retrieveMediator(DeputyMediator.NAME) as DeputyMediator;
			if(deputy==null) {
				deputy = new DeputyMediator();
				facade.registerMediator(deputy);
			}
			deputy.execInfo(view, deputyInfo);
			
		}
		
		private function execDeputyClear(e:Event=null):void
		{
			CommonAlert.showMsgYesNo("Approval", "대결자지정을 해제 하시겠습니까?", null, "ALERT_TITLE_DEFAULT", view, freeDeputy, null);
		}
		
		private function onSelectedApproval(e:Event):void
		{
			var medi:ApprovalViewMediator = facade.retrieveMediator(ApprovalViewMediator.NAME) as ApprovalViewMediator;
			if(medi==null) {
				medi = new ApprovalViewMediator();
				facade.registerMediator(medi);
			}
			var sEacc:String = view.viewToAppList.selectedItem.EVID;
			if(view.viewToAppList.selectedItem.WSTATUS == "2") {
				medi.execApproval(view,view.viewToAppList.selectedItem.GWAREKEY, sEacc);
			}
			else {				
				medi.execView(view, view.viewToAppList.selectedItem.GWAREKEY, sEacc);
			}
		}		
		
		private function onSelectedPreApproval(e:Event):void
		{
			var medi:ApprovalViewMediator = facade.retrieveMediator(ApprovalViewMediator.NAME) as ApprovalViewMediator;
			if(medi==null) {
				medi = new ApprovalViewMediator();
				facade.registerMediator(medi);
			}
			var sEacc:String = view.viewPreAppList.selectedItem.EVID;			
			medi.execView(view, view.viewPreAppList.selectedItem.GWAREKEY, sEacc);
		}		
		
		private function getSelectedAppList(arr:ArrayCollection):Array
		{
			var selArr:Array = [];
			for each(var rec:ApprovalListVO in arr) {
				if(rec.selected) {
					var vo:Object = new Object();
					
					vo.PROCGBN = rec.PROCGBN;
					vo.GWAREKEY = rec.GWAREKEY; 
					selArr.push(vo);
				}
			}
			return selArr;
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ApprovalOverView
        {
            return viewComponent as ApprovalOverView;
        }
	}
}